package com.graduation.project.service.group.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graduation.project.entity.dto.AddGroupDTO;
import com.graduation.project.entity.dto.AllotDefenseDTO;
import com.graduation.project.entity.po.DefenseGroup;
import com.graduation.project.entity.po.Thesis;
import com.graduation.project.entity.vo.ListDefenseVO;
import com.graduation.project.entity.vo.ListTaskOptionsVO;
import com.graduation.project.enums.ResultCodeEnum;
import com.graduation.project.mapper.group.DefenseMapper;
import com.graduation.project.mapper.process.ListThesisMapper;
import com.graduation.project.mapper.process.ThesisMapper;
import com.graduation.project.service.group.DefenseService;
import com.graduation.project.service.process.ThesisService;
import com.graduation.project.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DefenseServiceImpl extends ServiceImpl<DefenseMapper, DefenseGroup> implements DefenseService {

    @Autowired
    private DefenseMapper defenseMapper;
    @Autowired
    private ListThesisMapper listThesisMapper;
    @Autowired
    private ThesisMapper thesisMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultUtil<?> addGroup(AddGroupDTO addGroupDTO) {
        String groupCode = IdUtil.simpleUUID();
        List<DefenseGroup> defenseGroupList = new ArrayList<>();
        DefenseGroup defenseGroupLeader = new DefenseGroup();
        defenseGroupLeader.setGroupCode(groupCode);
        defenseGroupLeader.setGroupName(addGroupDTO.getGroupName());
        defenseGroupLeader.setUserCode(addGroupDTO.getGroupLeader());
        defenseGroupLeader.setUserType(0);
        defenseGroupList.add(defenseGroupLeader);

        if (CollUtil.isNotEmpty(addGroupDTO.getGroupMembers())) {
            for (String userCode : addGroupDTO.getGroupMembers()) {
                DefenseGroup defenseGroupMember = new DefenseGroup();
                defenseGroupMember.setGroupCode(groupCode);
                defenseGroupMember.setGroupName(addGroupDTO.getGroupName());
                defenseGroupMember.setUserCode(userCode);
                defenseGroupMember.setUserType(1);
                defenseGroupList.add(defenseGroupMember);
            }
        }
        try {
            this.saveBatch(defenseGroupList);
        }catch (Exception e) {
            throw new RuntimeException("新增失败");
        }

        return ResultUtil.Success(ResultCodeEnum.SUCCESS.getCode(), "新增成功");
    }

    @Override
    public ResultUtil<?> listDefenseGroup() {
        LambdaQueryWrapper<DefenseGroup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(DefenseGroup::getGroupCode)
                .groupBy(DefenseGroup::getGroupCode);
        List<DefenseGroup> groupCodeList = defenseMapper.selectList(lambdaQueryWrapper);

        List<Map<String, Object>> list = new ArrayList<>();
        for (DefenseGroup defenseGroup : groupCodeList) {
            lambdaQueryWrapper.clear();
            lambdaQueryWrapper.eq(DefenseGroup::getGroupCode, defenseGroup.getGroupCode());
            List<DefenseGroup> defenseGroupList = defenseMapper.selectList(lambdaQueryWrapper);

            List<ListDefenseVO> defenseVOList = new ArrayList<>();
            Map<String, Object> map = new HashMap<>();
            for (DefenseGroup group : defenseGroupList) {
                ListDefenseVO listDefenseVO = new ListDefenseVO();
                BeanUtil.copyProperties(group, listDefenseVO);
                defenseVOList.add(listDefenseVO);
            }
            map.put("listDefenseVo", defenseVOList);
            map.put("groupName", defenseVOList.get(0).getGroupName());
            map.put("groupCode", defenseVOList.get(0).getGroupCode());
            list.add(map);
        }

        return ResultUtil.Success(ResultCodeEnum.SUCCESS.getCode(), "查询成功", list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultUtil<?> updateGroupName(String groupCode, String groupName) {
        LambdaUpdateWrapper<DefenseGroup> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(DefenseGroup::getGroupName, groupName)
                .eq(DefenseGroup::getGroupCode, groupCode);

        try {
            defenseMapper.update(null, lambdaUpdateWrapper);
        }catch (Exception e) {
            throw new RuntimeException("修改失败");
        }
        return ResultUtil.Success(ResultCodeEnum.SUCCESS.getCode(), "修改成功");
    }

    @Override
    public ResultUtil<?> listFinalizeOptions(String groupCode) {
        List<ListTaskOptionsVO> listTaskOptionsVOS = listThesisMapper.listFinalizeOptions(groupCode);
        return ResultUtil.Success(ResultCodeEnum.SUCCESS, listTaskOptionsVOS);
    }

    @Override
    public ResultUtil<?> allotDefense(AllotDefenseDTO allotDefenseDTO) {
        LambdaQueryWrapper<Thesis> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Thesis::getGroupCode, allotDefenseDTO.getGroupCode());
        List<Thesis> thesisList = thesisMapper.selectList(lambdaQueryWrapper);

        List<Long> deleteList = new ArrayList<>();
        for (Thesis thesis : thesisList) {
            if (CollUtil.isEmpty(allotDefenseDTO.getTaskIds())) {
                deleteList.add(thesis.getTaskId());
            }else {
                for (Long taskId : allotDefenseDTO.getTaskIds()) {
                    if (thesis.getTaskId().equals(taskId)) {
                        break;
                    }
                    // 需要删除的集合
                    deleteList.add(thesis.getTaskId());
                }
            }
        }

        LambdaUpdateWrapper<Thesis> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        // 新增、修改
        for (Long taskId : allotDefenseDTO.getTaskIds()) {
            lambdaUpdateWrapper.set(Thesis::getGroupCode, allotDefenseDTO.getGroupCode())
                    .eq(Thesis::getTaskId, taskId)
                    .eq(Thesis::getThesisType, 1)
                    .eq(Thesis::getAuditStatus, 1);
            try {
                thesisMapper.update(null, lambdaUpdateWrapper);
            }catch (Exception e) {
                throw new RuntimeException("分配失败");
            }
        }

        // 删除
        for (Long taskId : deleteList) {
            lambdaUpdateWrapper.clear();
            lambdaUpdateWrapper.set(Thesis::getGroupCode, "")
                    .eq(Thesis::getTaskId, taskId)
                    .eq(Thesis::getThesisType, 1)
                    .eq(Thesis::getAuditStatus, 1);
            try {
                thesisMapper.update(null, lambdaUpdateWrapper);
            }catch (Exception e) {
                throw new RuntimeException("分配失败");
            }
        }

        return ResultUtil.Success(ResultCodeEnum.SUCCESS.getCode(), "分配成功");
    }

    @Override
    public ResultUtil<?> listMySelfFinalize(String groupCode) {
        LambdaQueryWrapper<Thesis> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Thesis::getGroupCode, groupCode);

        List<Thesis> thesisList = thesisMapper.selectList(lambdaQueryWrapper);

        List<Long> taskIds = new ArrayList<>();
        for (Thesis thesis : thesisList) {
            taskIds.add(thesis.getTaskId());
        }
        return ResultUtil.Success(ResultCodeEnum.SUCCESS, taskIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultUtil<?> deleteGroup(String groupCode) {
        LambdaQueryWrapper<DefenseGroup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DefenseGroup::getGroupCode, groupCode);
        try {
            defenseMapper.delete(lambdaQueryWrapper);
        }catch (Exception e) {
            throw new RuntimeException("删除失败");
        }
        return ResultUtil.Success(ResultCodeEnum.SUCCESS.getCode(), "删除成功");
    }
}
